<?php
/**
 * Created by PhpStorm.
 * User: mingzhongshui
 * Date: 2020/3/31
 * Time: 21:05
 */

namespace App\Console\Commands\User;

use App\Repositories\User\UserRepository;
use App\Repositories\User\UserVipRemindTimeRepository;
use App\Services\Wechat;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

/**
 *
 * Class VipExpireRemind
 * @package App\Console\Commands\User
 */
class VipExpireRemind extends Command
{

    protected $signature = 'user:vip:expireRemind';

    protected $description = 'vip expire remind';

    private $userRepository;
    
    private $userVipRemindTimeRepository;

    private $wx;

    private $logger;

    /**
     * VipExpireRemind constructor.
     * @param UserRepository $userRepository
     * @param UserVipRemindTimeRepository $userVipRemindTimeRepository
     */
    public function __construct(UserRepository $userRepository, UserVipRemindTimeRepository $userVipRemindTimeRepository)
    {
        parent::__construct();

        $this->userRepository = $userRepository;
        
        $this->userVipRemindTimeRepository = $userVipRemindTimeRepository;

        $this->wx = new Wechat();

        $this->logger = Log::channel('console');
    }

    /**
     * 是否可以发送
     * 
     * @param $uid
     * @return bool
     */
    private function isCanSend($uid)
    {
        $datetime = (new Carbon())->toDateTimeString();
        
        $res = $this->userVipRemindTimeRepository->getOneByUid($uid);
        
        if (!$res) {
            $this->userVipRemindTimeRepository->insert(['uid' => $uid, 'datetime' => $datetime]);
            
            return true;
        }
        
        $newDatetime = (new Carbon($res['datetime'] ))->addDays(7)->toDateTimeString();
        
        if ($newDatetime > $datetime) {
            return false;
        }
        
        return true;
    }

    /**
     * @throws \Exception
     */
    public function handle()
    {
        foreach ($this->userRepository->getNeedRemindVipUser() as $user) {
        
            try {
                
                if ($this->isCanSend($user['id'])) {
                    $this->wx->sendWxTplMsg($user->open_id, '您的天集社会员权益即将到期');
                }
        
            } catch (\Exception $e) {
                
                $this->logger->error($this->signature, [$e->getMessage(), $user]);
                
                $this->error($e->getMessage());
            }
        }

        $this->info($this->signature . ' success！'. (new Carbon())->toDateTimeString());
    }
}